<?php

/* Start session if it isn't already started */
if(!isset($_SESSION))
{
  session_start();
}

error_reporting(E_ALL);
ini_set('display_errors', '1');

/* Include connection to DB */
include_once("../includes/config.inc.php");
include_once(MYSQL);

/* Start session if it isn't already started */
if(!isset($_SESSION['email']))
{
  if(!headers_sent())
  {
    header('Location: ../login.php');
  }
  else
  {
    echo "<script>window.location.replace('../vineyard.php');</script>";
  }
}

if($_SERVER['REQUEST_METHOD'] == "POST")
{
  if(isset($_SESSION['email'], $_POST['vineyard_id'], $_POST['comments'], 
           $_POST['rating'], $_SESSION['id']))
  {

    $q = "SELECT vineyard_id FROM VineyardChecklist WHERE user_id = " . $_SESSION['id']
          . " AND vineyard_id = " . $_POST['vineyard_id'];
    $r = mysqli_query($dbc, $q);
    $row = mysqli_fetch_row($r);

    if(isset($row[0]))
    {
       /* The user has already reviewed this vineyard. */
       if(!headers_sent())
       {
         header('Location: ../vineyard.php?vineyard='. $_POST['vineyard_id'] . '&msg=0');
       }
       else
       {
         echo "<script>window.location.replace('../vineyard.php?vineyard=" 
              . $_POST['vineyard_id'] . "&msg=0');</script>";
       }
    }
    else
    {
      $id = $_SESSION['id'];
      $email = $_SESSION['email'];
      $vineyard_id = $_POST['vineyard_id'];
      $comments = $_POST['comments'];
      $rating = $_POST['rating'];
      
      $comments = strip_tags($comments);
      
      $q = "INSERT INTO Review (user_id, vineyard_id, category, comment, review)
            VALUES (?, ?, 'vineyard', ?, ?);";

      $stmt = mysqli_prepare($dbc, $q);
      mysqli_stmt_bind_param($stmt, 'iisi', $id, $vineyard_id, $comments, $rating);
      mysqli_stmt_execute($stmt);
      mysqli_stmt_close($stmt);

      $q = "INSERT INTO VineyardChecklist (user_id, vineyard_id) VALUES (?, ?);";

      $stmt = mysqli_prepare($dbc, $q);
      mysqli_stmt_bind_param($stmt, 'ii', $id, $vineyard_id);
      mysqli_stmt_execute($stmt);
      mysqli_stmt_close($stmt); 
     
      /* Redirect the user back to the vineyard page with a success message */
      if(!headers_sent())
      {
        header('Location: ../vineyard.php?vineyard='. $_POST['vineyard_id'] . '&msg=1');
      }
      else
      {
        echo "<script>window.location.replace('../vineyard.php?vineyard=" 
             . $_POST['vineyard_id'] . "&msg=1')</script>";
      }
    } 
  }
}

?>
